# -*- coding = utf-8 -*-
#@Time: 2020/10/23 11:55
#@Author: 卜白
#@File: view.py
#@Software: PyCharm

# 密码加密
import os

from werkzeug.security import generate_password_hash,check_password_hash
from werkzeug.utils import secure_filename
from flask import Blueprint, render_template, request, redirect, url_for, jsonify,session,g,make_response
from settings import Config     # 配置文件
from exts import db
from apps.user.models import *  # 模型

# 验证码
from io import BytesIO
from apps.utils.util import generate_image, upload_qiniu, delete_qiniu

user_bp = Blueprint('user_bp',__name__,url_prefix='/user')  # url_prefix添加固定参数路由user
required_login_list = [
    '/user/center',     # 用户中心
    '/user/modify',     # 用户中心——信息修改
    '/user/upload_photo', # 用户中心——上传照片
    '/user/del_photo', # 用户中心——删除照片
    # '/house/index',
    # '/house/ershoufang',
    # '/house/dealershouhouse',
    # '/house/newhouse',
    # '/house/renthouse'
]
# 重点  权限验证（查看登录状态）
@user_bp.before_app_request
def first_request():
    # request.path浏览过网页的路由路径
    # print('before_app_request：',request.path)\
    city = session.get('city')  # 从会话中获取city
    if request.path in required_login_list:
        id = session.get('userid')
        if not id:
            return render_template('user/login.html',city=city)
        else:
            user = User.query.get(id)
            # g对象，本次请求的对象（过了本次请求后对象就不好使）
            g.user = user

# 用户注册
@user_bp.route('/register',methods=['GET','POST'])
def register():
    city = session.get('city')    # 从会话中获取city
    if request.method == 'POST':
        username = request.form.get('username')
        password = request.form.get('password')
        repassword = request.form.get('repassword')
        phone = request.form.get('phone')
        email = request.form.get('email')
        if password == repassword:
            user = User()   # 用户表模型
            # 赋值
            user.username = username
            # 使用自带的函数实现加密：generate_password_hash
            user.password = generate_password_hash(password)    # 底层是sha256
            user.phone = phone
            user.email = email

            # 添加
            # 将user对象添加到session中（类似缓存）
            db.session.add(user)
            # 提交数据
            db.session.commit()

            # 注册成功 redirect跳转
            return redirect(url_for('user_bp.login'))
        else:
            return render_template('user/register.html',city=city,alerts='两次密码不一致，请重新输入！')

    return render_template('user/register.html',city=city)

# 注册-手机号码验证
@user_bp.route('/check_phone',methods=['GET','POST'])
def check_phone():
    phone = request.args.get('phone')
    user = User.query.filter(User.phone == phone).all()
    # code: 404不能用  200可以用
    if user:
        # jsonify底层封装了json.dumps  序列化
        return jsonify(code=404,error='此号码已被注册')
    else:
        return jsonify(code=200,error='此号码可用')
    
# 用户登录
@user_bp.route('/login', methods=['GET', 'POST'])
def login():
    city = session.get('city')    # 从会话中获取city
    if request.method == 'POST':
        username = request.form.get('username')
        password = request.form.get('password')
        users = User.query.filter(User.username == username).all()
        for user in users:
            # 如果flag=True表示匹配，否则密码不匹配
            flag = check_password_hash(user.password, password)
            if flag:
                session['userid'] = user.id
                return redirect(url_for('user_bp.user_center'))
            else:
                return render_template('user/login.html', msg='用户名或者密码有误',city=city)
    return render_template('user/login.html',city=city)

# 获取验证码
@user_bp.route('/image')
def get_image():
    # im：图片验证码   code：验证码
    im,code = generate_image(4)
    # 将image对象转化为二进制
    buffer = BytesIO()
    im.save(buffer,'JPEG')
    buf_bytes = buffer.getvalue()
    # 保存验证码到session中
    session['valid'] = code

    response = make_response(buf_bytes)
    response.headers['Content-Type'] = 'image/jpg'
    response.headers['Verification-Code'] = code
    return response

# 验证码-验证
@user_bp.route('/check_verifi',methods=['GET','POST'])
def check_verifi():
    verifi = session.get('valid')        # 获取登录页面渲染的验证码
    if verifi:
        return jsonify(verifi=verifi)

# 用户退出
@user_bp.route('/logout')
def logout():
    del session['userid']   # 退出只去掉session会话中的userid值  即用户
    # session.clear()       # 退出整个session会话
    return redirect(url_for('user_bp.login'))

# 用户中心
@user_bp.route('/center')
def user_center():
    city = session.get('city')  # 从会话中获取city
    photos = Photo.query.filter(Photo.user_id == g.user.id).all()
    return render_template('user/center.html',user=g.user,city=city,photos=photos)

ALLOWED_EXTENSIONS = ['jpg', 'png', 'gif', 'bmp']  # 允许存在的后缀名（图片的扩展名）
# 用户信息修改
@user_bp.route('/modify',methods=['GET','POST'])
def info_modify():
    city = session.get('city')  # 从会话中获取city
    if request.method == 'POST':
        username = request.form.get('username')
        phone = request.form.get('phone')
        email = request.form.get('email')
        # 只要有图片（文件上传类型），获取方式必须使用request.files.get(name)
        icon = request.files.get('icon')
        # print('==========>',icon)   # 返回FileStorage类型
        # 属性：filename 用户获取文件的名字
        # 方法：save（保存路径）
        icon_name = icon.filename
        suffix = icon_name.rsplit('.')[-1]  # 取文件后缀名
        # print('图片后缀名：',suffix)
        if suffix in ALLOWED_EXTENSIONS:
            # secure_filename：安全的文件名，是指传入的文件若存在错误，可自动补全为安全的格式名
            icon_name = secure_filename(icon_name)  # 保证文件名是符合Python的命名规则
            # print('文件名：',icon_name)
            file_path = os.path.join(Config.UPLOAD_ICON_DIR,icon_name)
            file_path = file_path.replace('\\','/')
            # print('路径：',file_path)
            icon.save(file_path)    # 将图片保存到指定路径成功

            # 更新数据库数据
            user = g.user
            user.username = username
            user.phone = phone
            user.email = email
            path = 'upload/icon'
            user.icon = os.path.join(path,icon_name).replace('\\','/')
            db.session.commit()
            return redirect(url_for('user_bp.user_center'))

        else:
            return render_template('user/center.html',city=city, user=g.user, msg='头像文件的扩展名必须是：jpg,png,gif,bmp格式')


    return render_template('user/center.html',city=city, user=g.user)

# 上传相册
@user_bp.route('/upload_photo',methods=['GET','POST'])
def upload_photo():
    city = session.get('city')  # 从会话中获取city
    # 获取上传的内容（文件）
    photo = request.files.get('photo')  # FileStorage
    # photo.filename,photo.save(path)
    # 七牛对象存储——上传图片
    result,info = upload_qiniu(photo)
    if info.status_code == 200:
        photo = Photo()  # 照片表
        photo.photo_name = result['key']
        photo.user_id = g.user.id
        db.session.add(photo)
        db.session.commit()

        return redirect(url_for('user_bp.user_center'))
    else:
        return render_template('user/center.html',city=city, user=g.user, msg='图片上传失败！！！')

# 删除图片
@user_bp.route('del_photo')
def del_photo():
    pid = request.args.get('pid')
    # print('pid：',pid)
    photo = Photo.query.get(pid)
    filename = photo.photo_name
    # 封装好的一个删除七牛存储文件的函数
    info = delete_qiniu(filename)
    # 判断状态码
    if info.status_code == 200:
        # 删除数据的内容
        db.session.delete(photo)
        db.session.commit()
        return redirect(url_for('user_bp.user_center'))
    else:
        return render_template('error.html',error='删除相册照片失败！')

# 错误处理404
@user_bp.route('/error')
def test_error():
    # print(request.headers)
    # print(request.headers.get('Accept-Encoding'))
    referer = request.headers.get('Referer',None)
    return render_template('error.html',error='404未找到页面 ',referer=referer)